package com.ee.chat.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.admin.service.IAdminUserService;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.AdminRoleMapper;
import com.ee.chat.common.dao.AdminUserMapper;
import com.ee.chat.common.entity.AdminRole;
import com.ee.chat.common.entity.AdminUser;
import com.ndhutu.ee.util.MD5Util;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminUserService implements IAdminUserService {
    @Resource
    AdminUserMapper adminUserMapper;
    @Resource
    AdminRoleMapper adminRoleMapper;
    @Resource
    IOperationService operationService;

    @Override
    public Result list(HttpServletRequest request, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        IPage<Map<String, Object>> iPage = adminUserMapper.getAdminUsers(new Page<>(page, limit));

        data.put("users", iPage.getRecords());
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "获取管理员数据列表");

        return Result.returnSuccess(data);
    }

    @Override
    public Result del(HttpServletRequest request, List<Integer> ids) throws Exception {
        for(Integer id : ids){
            AdminUser adminUser = adminUserMapper.selectById(id);
            if(adminUser.getSystem() == 1){
                return Result.returnFailure("超级管理员为系统内置用户，不能删除");
            }
        }

        adminUserMapper.deleteBatchIds(ids);

        operationService.addOperationLog(request, "删除管理员，ids："+ids);

        return Result.returnSuccess(null);
    }

    @Override
    public Result toEdit(HttpServletRequest request, Integer id) throws Exception {
        Map<String, Object> data = new HashMap<>();

        AdminUser adminUser = adminUserMapper.selectById(id);
        data.put("adminUser", adminUser);

        //用户拥有的角色
        List<AdminRole> userRoles = null;
        if(id != null){
            userRoles = adminUserMapper.getUserRoles(id);
        }
        data.put("userRoles", userRoles);

        //系统全部角色
        QueryWrapper<AdminRole> wrapper = new QueryWrapper<>();
        wrapper.eq("`status`", 0);
        wrapper.orderByDesc("order_id");
        List<AdminRole> roles = adminRoleMapper.selectList(wrapper);
        data.put("roles", roles);

        return Result.returnSuccess(data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result edit(HttpServletRequest request, AdminUser adminUser) throws Exception {
        AdminUser user = adminUserMapper.selectById(adminUser.getId());
        user.setNickname(adminUser.getNickname());
        user.setRealname(adminUser.getRealname());
        adminUserMapper.updateById(user);

        //更新角色
        adminUserMapper.deleteUserRoleByUserId(adminUser.getId());
        List<Integer> roleIds = JSON.parseArray(adminUser.getRoleIds(), Integer.class);
        List<Map<String, Object>> userRoles = new ArrayList<>();
        for(Integer roleId : roleIds){
            Map<String, Object> userRole = new HashMap<>();
            userRole.put("userId", adminUser.getId());
            userRole.put("roleId", roleId);
            userRoles.add(userRole);
        }
        adminUserMapper.batchAddUserRole(userRoles);

        operationService.addOperationLog(request, "编辑管理员，id："+adminUser.getId());

        return Result.returnSuccess(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result save(HttpServletRequest request, AdminUser adminUser) throws Exception {
        AdminUser user = adminUserMapper.getAdminUserByUsername(adminUser.getUsername());
        if(user != null){
            return Result.returnFailure("该用户名已经占用，请更换其他用户名");
        }

        adminUser.setPassword(MD5Util.encode32(adminUser.getPassword()));
        adminUserMapper.insert(adminUser);

        List<Integer> roleIds = JSON.parseArray(adminUser.getRoleIds(), Integer.class);
        List<Map<String, Object>> userRoles = new ArrayList<>();
        for(Integer roleId : roleIds){
            Map<String, Object> userRole = new HashMap<>();
            userRole.put("userId", adminUser.getId());
            userRole.put("roleId", roleId);
            userRoles.add(userRole);
        }
        adminUserMapper.batchAddUserRole(userRoles);

        operationService.addOperationLog(request, "新增管理员，id："+adminUser.getId());

        return Result.returnSuccess(null);
    }

    @Override
    public Result restPwd(HttpServletRequest request, Integer id) throws Exception {
        AdminUser adminUser = adminUserMapper.selectById(id);
        if(adminUser.getSystem() == 1){
            return Result.returnFailure("系统内置管理员用户不能重置密码");
        }

        adminUser.setPassword(MD5Util.encode32("123456"));
        adminUserMapper.updateById(adminUser);

        operationService.addOperationLog(request, "编辑管理员，id："+id);

        operationService.addOperationLog(request, "重置密码");

        return Result.returnSuccess(null);
    }

    @Override
    public Result changeStatus(HttpServletRequest request, Integer id) throws Exception {
        AdminUser adminUser = adminUserMapper.selectById(id);
        if(adminUser.getSystem() == 1){
            return Result.returnFailure("系统内置管理员用户不能更改状态");
        }

        HttpSession session = request.getSession(true);
        AdminUser user = (AdminUser) session.getAttribute("adminUser");
        if(user.getId().equals(id)){
            return Result.returnFailure("不能更改当前登录用户的状态");
        }

        if(adminUser.getStatus() == 0){
            adminUser.setStatus(1);
        }else{
            adminUser.setStatus(0);
        }
        adminUserMapper.updateById(adminUser);

        operationService.addOperationLog(request, "变更管理员状态，id："+id);

        return Result.returnSuccess(null);
    }
}
